﻿#region File and License Information
/*
<File>
	<License Type="BSD">
		Copyright © 2009 - 2012, Daniel Vaughan. All rights reserved.
	
		This file is part of Calcium (http://calciumsdk.net).

		Redistribution and use in source and binary forms, with or without
		modification, are permitted provided that the following conditions are met:
			* Redistributions of source code must retain the above copyright
			  notice, this list of conditions and the following disclaimer.
			* Redistributions in binary form must reproduce the above copyright
			  notice, this list of conditions and the following disclaimer in the
			  documentation and/or other materials provided with the distribution.
			* Neither the name of the <organization> nor the
			  names of its contributors may be used to endorse or promote products
			  derived from this software without specific prior written permission.

		THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
		ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
		WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
		DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
		DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
		(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
		LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
		ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
		(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
		SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	</License>
	<Owner Name="Daniel Vaughan" Email="danielvaughan@outcoder.com" />
	<CreationDate>2012-07-21 09:41:27Z</CreationDate>
</File>
*/
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;

namespace DanielVaughan.ComponentModel
{
	/// <summary>
	/// This class is analagous to the Knockout JS style computed observables. 
	/// It is used to wrap a value and provides change notification for bindings 
	/// without adding plumbing to a viewmodel. 
	/// This class allows you to provide an expression that is parsed to locate associated objects 
	/// that implement <c>INotifyPropertyChanged</c>. When a change notification is received 
	/// from any such objects, the value of the expression is recomputed.
	/// Disposing of this object removes subscriptions to all associated objects.
	/// <see cref="http://danielvaughan.org/post/Knockout-Style-Observables-in-XAML.aspx" />
	/// <seealso cref="ObservableValue{T}"/>
	/// </summary>
	/// <example>
	/// class MainWindowViewModel
	///{
	///    public MainWindowViewModel()
    ///	   {
    ///			fullName = new ComputedValue&lt;string&gt;(() => FirstName.Value + " " + ToUpper(LastName.Value));
    ///	   }
	/// ...
	/// }
	/// Bind to the value in XAML using:
	/// &lt;TextBlock Text="{Binding Path=FullName.Value}" /&gt;
	/// </example>
	/// <typeparam name="T">The type of result returned from executing the specified expression.</typeparam>
	public class ComputedValue<T> : INotifyPropertyChanged, IDisposable
	{
		readonly Dictionary<PropertyChangedEventHandler, WeakReference> handlers
					= new Dictionary<PropertyChangedEventHandler, WeakReference>();

		readonly Func<T> valueFunc;

		/// <summary>
		/// Gets the value by executing the Lambda Expression that was supplied to the constructor.
		/// </summary>
		public T Value
		{
			get
			{
				T result = valueFunc();
				return result;
			}
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="ComputedValue&lt;T&gt;"/> class.
		/// </summary>
		/// <param name="expression">The expression that is evaluated when the value of this object is requested.
		/// Any associated objects that implement <c>INotifyPropertyChanged</c> are automatically subscribed to.</param>
		public ComputedValue(Expression<Func<T>> expression)
		{
			if (expression == null)
			{
				throw new ArgumentNullException("expression");
			}

			Expression body = expression.Body;

			ProcessDependents(body);

			valueFunc = expression.Compile();
		}

		void ProcessDependents(Expression expression)
		{
			switch (expression.NodeType)
			{
				case ExpressionType.Negate:
				case ExpressionType.NegateChecked:
				case ExpressionType.Not:
				case ExpressionType.Convert:
				case ExpressionType.ConvertChecked:
				case ExpressionType.ArrayLength:
				case ExpressionType.Quote:
				case ExpressionType.TypeAs:
					ProcessUnaryExpression((UnaryExpression)expression);
					break;
				case ExpressionType.Add:
				case ExpressionType.AddChecked:
				case ExpressionType.Subtract:
				case ExpressionType.SubtractChecked:
				case ExpressionType.Multiply:
				case ExpressionType.MultiplyChecked:
				case ExpressionType.Divide:
				case ExpressionType.Modulo:
				case ExpressionType.And:
				case ExpressionType.AndAlso:
				case ExpressionType.Or:
				case ExpressionType.OrElse:
				case ExpressionType.LessThan:
				case ExpressionType.LessThanOrEqual:
				case ExpressionType.GreaterThan:
				case ExpressionType.GreaterThanOrEqual:
				case ExpressionType.Equal:
				case ExpressionType.NotEqual:
				case ExpressionType.Coalesce:
				case ExpressionType.ArrayIndex:
				case ExpressionType.RightShift:
				case ExpressionType.LeftShift:
				case ExpressionType.ExclusiveOr:
					ProcessBinaryExpression((BinaryExpression)expression);
					break;
				//				case ExpressionType.TypeIs:
				//					return this.ProcessTypeIs((TypeBinaryExpression)expression);
				//				case ExpressionType.Conditional:
				//					return this.ProcessConditional((ConditionalExpression)expression);
				//				case ExpressionType.Constant:
				//					return this.ProcessConstant((ConstantExpression)expression);
				//				case ExpressionType.Parameter:
				//					return this.ProcessParameter((ParameterExpression)expression);
				case ExpressionType.MemberAccess:
					ProcessMemberAccessExpression((MemberExpression)expression);
					break;
				case ExpressionType.Call:
					ProcessMethodCallExpression((MethodCallExpression)expression);
					break;
				//				case ExpressionType.Lambda:
				//					return this.ProcessLambda((LambdaExpression)expression);
				//				case ExpressionType.New:
				//					return this.ProcessNew((NewExpression)expression);
				//				case ExpressionType.NewArrayInit:
				//				case ExpressionType.NewArrayBounds:
				//					return this.ProcessNewArray((NewArrayExpression)expression);
				//				case ExpressionType.Invoke:
				//					return this.ProcessInvocation((InvocationExpression)expression);
				//				case ExpressionType.MemberInit:
				//					return this.ProcessMemberInit((MemberInitExpression)expression);
				//				case ExpressionType.ListInit:
				//					return this.ProcessListInit((ListInitExpression)expression);
				default:
					return;
			}
		}

		void ProcessMethodCallExpression(MethodCallExpression expression)
		{
			foreach (Expression argumentExpression in expression.Arguments)
			{
				ProcessDependents(argumentExpression);
			}
		}

		void ProcessUnaryExpression(UnaryExpression expression)
		{
			ProcessDependents(expression.Operand);
		}

		void ProcessBinaryExpression(BinaryExpression binaryExpression)
		{
			Expression left = binaryExpression.Left;
			Expression right = binaryExpression.Right;
			ProcessDependents(left);
			ProcessDependents(right);
		}

		void ProcessMemberAccessExpression(MemberExpression expression)
		{
			Expression ownerExpression = expression.Expression;
			Type ownerExpressionType = ownerExpression.Type;

			if (typeof(INotifyPropertyChanged).IsAssignableFrom(ownerExpressionType))
			{
				try
				{
					string memberName = expression.Member.Name;
					PropertyChangedEventHandler handler = delegate(object sender, PropertyChangedEventArgs args)
					{
						if (args.PropertyName == memberName)
						{
							OnValueChanged();
						}
					};

					var owner = (INotifyPropertyChanged)GetValue(ownerExpression);
					owner.PropertyChanged += handler;

					handlers[handler] = new WeakReference(owner);
				}
				catch (Exception ex)
				{
					Console.WriteLine("ComputedValue failed to resolve INotifyPropertyChanged value for property {0} {1}",
									  expression.Member, ex);
				}
			}
		}

		object GetValue(Expression expression)
		{
			UnaryExpression unaryExpression = Expression.Convert(expression, typeof(object));
			Expression<Func<object>> getterLambda = Expression.Lambda<Func<object>>(unaryExpression);
			Func<object> getter = getterLambda.Compile();

			return getter();
		}

		public event PropertyChangedEventHandler PropertyChanged;

		void OnPropertyChanged(string propertyName)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null)
			{
				handler(this, new PropertyChangedEventArgs(propertyName));
			}
		}

		void OnValueChanged()
		{
			OnPropertyChanged("Value");
		}

		bool disposed;

		protected virtual void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (disposing)
				{
					foreach (KeyValuePair<PropertyChangedEventHandler, WeakReference> pair in handlers)
					{
						INotifyPropertyChanged target = pair.Value.Target as INotifyPropertyChanged;
						if (target != null)
						{
							target.PropertyChanged -= pair.Key;
						}
					}

					handlers.Clear();
				}

				disposed = true;
			}
		}

		public void Dispose()
		{
			Dispose(true);
		}
	}
}